You have to hand it to Microsoft for going above and
beyond in some areas of Azure. The fact that it provides you with
connection strings to use in your applications is just plain cool. As
soon as you select a database in the list, the Connection Strings
button becomes enabled. Clicking it brings up the dialog shown in Figure 1,
which provides you with two connections strings (one .NET and the other
ODBC) to use in your applications to connect to the selected SQL Azure
database.
This section uses the
ADO.NET connection string to create an ADO.NET 4.0 Entity Framework
application. You also use Visual Studio 2010, which at the time of this
writing is a release candidate and available to everyone, and which
should be available by the time this book is in your hands.
Before you start
building your application, you need a database with data in it. Based on
what you've learned in this article, create a new SQL Azure database
named EFAzure. Next, open the SQL file for this article called CreateContactTable.sql,
and run that script against the EFAzure database. The script creates a
single table called Contact and inserts about a dozen contact records.
The examples in the
following two sections illustrate connecting to a SQL Azure database
and querying the database for contact records. The first example uses
the ADO.NET connection string shown in Figure 3-12,
and the second uses the ADO.NET 4.0 Entity Framework. You have many
options to connect to a SQL Azure database, and this article shows you
simple examples.
1. Connecting Using ADO.NET
In this first example, you
build a simple Windows Forms application and use ADO.NET to query the
EFAzure SQL Azure database. Follow these steps:
Open Visual Studio 2010, and create a new Windows Forms Application project.
Open Form1 in design mode, and place a button and a ListBox on the form.
Double-click the button to view its Click event, and enter the following code. Copy the ADO.NET connection string for your database from the dialog shown in Figure 3-12, and use it to replace the bolded section shown in the code:
using (SqlConnection conn = new
SqlConnection("Server=tcp:servername.database.windows.net;Database=EFAzure;User
ID=userid;Password=mypassword;Trusted_Connection=False;Encrypt=True;"))
{
try
{
SqlCommand cmd = new SqlCommand(@"SELECT FirstName, LastName
FROM Contact
ORDER BY LastName", conn);
cmd.Connection.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
listBox1.Items.Add(String.Format("{0} {1}", rdr[0], rdr[1]));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
When the code is in place, run
the application. When Form1 appears, click the button; doing so should
quickly display in the list box the first name and last name of the
contacts from the Contact table. As you can see, the code is the same as
if you were querying a local SQL Server database, except for the
connection string.